#include "mystdio.h"

MyFILE* MyFopen(const char* filename,const char* mode)
{
  mode_t MyMode =0666;
  int Mode = 0;
  int IsCreat=0;
  if(strcmp(mode,"r")==0)
  {
    Mode =O_RDONLY;
 
  }
  else if(strcmp(mode,"w")==0)
  {
    Mode =O_WRONLY | O_CREAT | O_TRUNC;
    IsCreat = 1;
  }
  else if(strcmp(mode,"a")==0)
  {
    Mode =O_WRONLY | O_CREAT | O_APPEND;
    IsCreat = 1;

  }
  else
  {};
  int fd = -1;
  if(IsCreat)
  {
   fd= open(filename,Mode,MyMode);
  }
  else
  {
    fd=open(filename,Mode);
  }
  if(fd==-1)
  {
    perror("open GG");
    return NULL;
  }

  MyFILE* f =(MyFILE*)malloc(sizeof(MyFILE));
  if(!f)
  {
    perror("malloc GG");
    return NULL;
  }
  f->cap = MySize;
  f->fileno =fd;
  f->pos = 0;
  return f;
           
}
void MyFlush(MyFILE* f)
{
  write(f->fileno,f->cache,f->pos);
  f->pos =0;
}
size_t MyWrite(MyFILE* f,const char* data,size_t length)
{
  memcpy(f->cache+f->pos,data,length);
  f->pos+=length;
  if(f->pos!=0)
  if(f->cache[f->pos-1]=='\n')
  {
    MyFlush(f);
  }
  return length;


}

void MyClose(MyFILE* f)
{
  MyFlush(f);
  close(f->fileno);
  free(f);
  
}



